#pragma once

#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<unistd.h>
#include<cstring>
#include<arpa/inet.h>
#include<netinet/in.h>


using namespace std;

class TcpClient
{
  //客户端要连接服务端，需要知道服务端的ip的地址和端口号
  private:
    string svr_ip;
    int svr_port;
    int sock;
  public:
   TcpClient(string _ip,int _port)
     :svr_ip(_ip)
     ,svr_port(_port)
     ,sock(-1)
     {}
   //初始化接口，需要链接置tcpduankou
   bool init_tcp_client()
   {
      sock=socket(AF_INET,SOCK_STREAM,0);
      if(sock<0)
      {
        cout<<"tcp_client sock create fail"<<endl;
        return false;
      }

      return true;
   }
   void start()
   {
      struct sockaddr_in local;
      memset(&local,0,sizeof(local));
      local.sin_family=AF_INET;
      local.sin_port=htons(svr_port);
      local.sin_addr.s_addr=inet_addr(svr_ip.c_str());//将本地地址转换成网络地址  点分十进制iP转换成长整形
      
      //链接网络ip
      if(connect(sock,(struct sockaddr*)&local,sizeof(local))==0)
      {
        //链接成功，执行请求
        cout<<"connect success"<<endl;
        request(sock);
      }
      else
      {
        cout<<"connect fail"<<endl;
      }
   }
   void request(int sockfd)
   {
     string message;
     char buffer[1024];
     while(true)
     {
       cout<<"please enter# ";
       cin>>message;
       write(sockfd,message.c_str(),message.size());
       ssize_t size=read(sockfd,buffer,sizeof(buffer)-1);
       if(size>0)
       {
         buffer[size]=0;
         cout<<"sever echo"<<buffer<<endl;
       }
     }
   }
   ~TcpClient()
   {
     if(sock>=0)
     {
      close(sock);
     }
   }

};
